package ui.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;

import domein.DomeinController;
import domein.exceptie.SpelbordAlreadyExistsException;

public class MaakNieuweMap extends JDialog implements ActionListener{

	private ResourceBundle resourceBundle;
	
	private JTextField txtMapNaam;
	private JLabel lblNaam, lblBreedte, lblHoogte;
	private JSpinner spnBreedte, spnHoogte;
	private JButton btnBevestig, btnCancel;	
	private KiesSpelbord owner;
	
	public MaakNieuweMap(KiesSpelbord owner, ResourceBundle resourceBundle){
		super(owner, "Maak een nieuwe map");
		this.setLayout(new BorderLayout());
		
		this.resourceBundle = resourceBundle;
		this.owner = owner;
		
		this.initComponents();
		
		this.addComponents();
		
		this.setSize(210, 160);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}
	
	private void initComponents() {
		lblBreedte = new JLabel("Breedte:");
		lblHoogte = new JLabel("Hoogte:");
		lblNaam = new JLabel ("Geef een naam voor de nieuwe map:");
		spnBreedte = new JSpinner(new SpinnerNumberModel(10, 1, 99, 1));
		spnHoogte = new JSpinner(new SpinnerNumberModel(10, 1, 99, 1));
		
		btnBevestig = new JButton(resourceBundle.getString("bevestig"));
		btnBevestig.addActionListener(this);
		btnCancel = new JButton(resourceBundle.getString("annuleren"));
		btnCancel.addActionListener(this);		
		
		txtMapNaam = new JTextField(22);
	}
	
	private void addComponents(){
		JPanel pnlButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		pnlButtons.add(btnBevestig);
		pnlButtons.add(btnCancel);
		
		JPanel pnlMap = new JPanel(new FlowLayout());
		pnlMap.add(lblNaam);
		pnlMap.add(txtMapNaam);
		pnlMap.add(lblBreedte);
		pnlMap.add(spnBreedte);
		pnlMap.add(lblHoogte);
		pnlMap.add(spnHoogte);
		pnlMap.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
		
		this.add(pnlButtons, BorderLayout.SOUTH);
		this.add(pnlMap, BorderLayout.CENTER);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnCancel){
			this.dispose();
		}
		else if(e.getSource() == btnBevestig){
			try{
				DomeinController.getInstance().maakSpelbord(txtMapNaam.getText(), (Integer)spnBreedte.getValue(), (Integer)spnHoogte.getValue());
				
				owner.vulLijst();
				
				this.dispose();
			} catch(SpelbordAlreadyExistsException saee){
				JOptionPane.showMessageDialog(this, saee.getMessage());
				txtMapNaam.setText("");
			}			
		}
	}
}
